package com.example.listviwedemo;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener{
	 
	private Button btn;
	private ListView lv;
	List<Person> persons = new ArrayList<Person>();
	MyAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		btn = (Button) findViewById(R.id.btn);
		btn.setOnClickListener(this);
		lv = (ListView) findViewById(R.id.lv);
		adapter = new MyAdapter();
		lv.setAdapter(adapter);
	}

	@Override
	public void onClick(View v) {
		if(persons.size()<=0){
			persons.add(0,new Person("tom", 0));
		}else{
			if(persons.get(0).type == 1){
				persons.add(0,new Person("tom", 0));
			}else{
				persons.add(0,new Person("jack", 1));
			}
			if(persons.size()>3){
				persons.remove(persons.size()-1);
			}
		}
		adapter.notifyDataSetChanged();
	}
	
	
	class MyAdapter extends BaseAdapter{
		
		@Override
		public int getItemViewType(int position) {
			return persons.get(position).type;
		}

		@Override
		public int getViewTypeCount() {
			return 2;
		}

		@Override
		public int getCount() {
			return persons.size();
		}

		@Override
		public Object getItem(int position) {
			return persons.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			HoldView hv;
			if(convertView == null){
				hv = new HoldView();
				switch (getItemViewType(position)) {
				case 0:
					convertView = getLayoutInflater().inflate(R.layout.left, null);
					break;
				case 1:
					convertView = getLayoutInflater().inflate(R.layout.right, null);
					break;
				}
				hv.tv = (TextView) convertView.findViewById(R.id.item_tv);
				convertView.setTag(hv);
			}else{
				hv = (HoldView) convertView.getTag();
			}
			hv.tv.setText(persons.get(position).name);
			return convertView;
		}
	}
	
	class HoldView{
		TextView tv;
	}
}
